//
//  URL+AD.swift
//  ADKit
//
//  Created by Adoma on 2020/10/25.
//

import SwiftyJSON

public extension String {
    
    var toURL: URL? {
        
        if #available(iOS 17.0, *) {
            return URL(string: self, encodingInvalidCharacters: true)
        } else {
            return URL(string: self)
        }
    }
    
    var fileURL: URL? {
        URL(fileURLWithPath: self)
    }

}

public extension URL {
    
    
    /// append custom query from [String: Any]
    /// by ADKit
    func append(query: [String: String]) -> URL {
        
        var components = URLComponents(url: self, resolvingAgainstBaseURL: false)
        
        let items = query.map({ URLQueryItem(name: $0.key, value: $0.value) })
        
        var queryItems = components?.queryItems ?? []
        queryItems.append(contentsOf: items)
        
        components?.queryItems = queryItems
        
        return components?.url ?? self
    }
    
    /// k1=v1&k2=v2 to  {k1:v1, k2:v2}
    /// by ADKit
     var queryDictionary: [String: String]? {
         
         let components = URLComponents(url: self, resolvingAgainstBaseURL: false)
         
         return components?.queryItems?.reduce(into: [:]) { result, item in
             guard let value = item.value else {
                 return
             }
             result[item.name] = value
         }
    }
    
}
